package com.letv.core.utils;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;

/**
 * viewPager自动切换handler
 * 
 * @author zhuqiao
 *
 */
public abstract class AutoSwitchHandler extends Handler {
    /** viewpager自动切换观察者 **/
    public static final AutoSwitchObservable autoScrollObservable = new AutoSwitchObservable();

    private static final int SWITCH = 1;
    /**
     * 滑动间隔时间默认值
     */
    private static final int DEFAULT_AUTO_SWITCH_DELAY_TIME = 5 * 1000;

    /**
     * 自动切换的时间间隔
     */
    private final int mAutoSwitchDelay;

    /**
     * 自动切换功能是否使能
     */
    private boolean mIsEnabled;

    public AutoSwitchHandler() {
        this(DEFAULT_AUTO_SWITCH_DELAY_TIME);
    }

    public AutoSwitchHandler(int delay) {
        super();
        mAutoSwitchDelay = delay;

        autoScrollObservable.addHandler(this);
        mIsEnabled = true;
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == SWITCH && mIsEnabled) {
            next();
            onResume();
        }
    }

    /**
     * 开始
     */
    public void onResume() {
        removeCallbacksAndMessages(null);
        mIsEnabled = true;
        sendEmptyMessageDelayed(SWITCH, mAutoSwitchDelay);
    }

    /**
     * 暂停
     */
    public void onPause() {
        removeCallbacksAndMessages(null);
        mIsEnabled = false;
    }

    /**
     * 回收
     */
    public void onDestory() {
        onPause();
        autoScrollObservable.deleteHandler(this);
    }

    public boolean isEnabled() {
        return mIsEnabled;
    }

    public abstract void next();

    /**
     * 自动切换被观察者
     * 
     * @author user
     *
     */
    public static class AutoSwitchObservable {
        private List<AutoSwitchHandler> list = new ArrayList<AutoSwitchHandler>();

        /**
         * 添加观察者
         * 
         * @param handler
         */
        void addHandler(AutoSwitchHandler handler) {
            list.add(handler);
        }

        /**
         * 移除观察者
         * 
         * @param handler
         */
        void deleteHandler(AutoSwitchHandler handler) {
            list.remove(handler);
        }

        /**
         * 停止所有观察者
         */
        public void stopAll() {
            for (AutoSwitchHandler handler : list) {
                handler.onPause();
            }
        }

        /**
         * 停止并清除所有观察者
         */
        public void clearAll() {
            stopAll();
            list.clear();
        }
    }
}
